<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Payment extends CI_Controller {
    
    function Payment(){
        parent::__construct();
        $this->load->model('payment_model');
    }

    public function chargeInvoice() {

        // Load the library and config
        require_once(APPPATH . 'libraries/Stripe.php');
        $this->config->load('stripe');

        // Init the secret key.
        Stripe::setApiKey($this->config->item('stripe_secret_key'));

        $token = $_POST['stripeToken'];

        // Create the charge on Stripe's servers - this will charge the user's card

        $customer = Stripe_Customer::create(array(
                    'email' => 'customer@example.com',
                    'card' => $token
        ));

        $charge = Stripe_Charge::create(array(
                    'customer' => $customer->id,
                    'amount' => 5000,
                    'currency' => 'usd'
        ));
//        try {
//            $charge = Stripe_Charge::create(array(
//                        "amount" => 1000, // amount in cents, again
//                        "currency" => "usd",
//                        "card" => $token,
//                        "description" => "payinguser@example.com")
//            );
//        } catch (Stripe_CardError $e) {
//            // The card has been declined
//        }
        // $this->load->model('Item_model');
        // $rs = $this->Item_model->addItemEstimate();
        // echo json_encode($rs);
        echo $token;
    }

    public function pay($checkoutUid) {
        
        // Check for a form submission:
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {

            // Stores errors:
            $errors = array();

            // Need a payment token:
            if (isset($_POST['stripeToken'])) {

                $token = $_POST['stripeToken'];

                // Check for a duplicate submission, just in case:
                // Uses sessions, you could use a cookie instead.
                if ($this->session->userdata('token') && ($this->session->userdata('token') == $token)) {
                    $errors['token'] = 'You have apparently resubmitted the form. Please do not do that.';
                } else { // New submission.
                    $this->session->set_userdata('token', $token);
                }
            } else {
                $errors['token'] = 'The order cannot be processed. Please make sure you have JavaScript enabled and try again.';
            }

            // Set the order amount somehow:
            //$amount = 2000; // $20, in cents
            if ($checkoutUid){
                $estimateId = $this->payment_model->getEstimateId($checkoutUid);
                if ($estimateId){
                    // Get the amount of money and convert it to cent.
                    $amount = $this->payment_model->getAmount($estimateId)*100;
                    if (! $amount){
                        $errors['estimate'] = 'There are no payment';
                    }
                } else {
                    $errors['estimate'] = 'Could not find the Estimate';
                }
            } else {
                $errors['estimate'] = 'Could not find the Estimate';
            }
            
            
            // Validate other form data!
            // If no errors, process the order:
            if (empty($errors)) {

                // create the charge on Stripe's servers - this will charge the user's card
                try {

                    // Load the library and config
                    require_once(APPPATH . 'libraries/Stripe.php');
                    $this->config->load('stripe');

                    // set your secret key: remember to change this to your live secret key in production
                    // see your keys here https://manage.stripe.com/account
                    Stripe::setApiKey($this->config->item('stripe_secret_key'));

                    // Charge the order:
                    $charge = Stripe_Charge::create(array(
                                "amount" => $amount, // amount in cents, again
                                "currency" => "usd",
                                "card" => $token,
                                "description" => $checkoutUid
                            )
                    );

                    // Check that it was paid:
                    if ($charge->paid == true) {
                        // Store the order in the database.
                        
                    } else { // Charge was not paid!	
                        echo '<div class="alert alert-error"><h4>Payment System Error!</h4>Your payment could NOT be processed (i.e., you have not been charged) because the payment system rejected the transaction. You can try again or use another card.</div>';
                    }
                } catch (Stripe_CardError $e) {
                    // Card was declined.
                    $e_json = $e->getJsonBody();
                    $err = $e_json['error'];
                    $errors['stripe'] = $err['message'];
                } catch (Stripe_ApiConnectionError $e) {
                    // Network problem, perhaps try again.
                } catch (Stripe_InvalidRequestError $e) {
                    // You screwed up in your programming. Shouldn't happen!
                } catch (Stripe_ApiError $e) {
                    // Stripe's servers are down!
                } catch (Stripe_CardError $e) {
                    // Something else that's not the customer's fault.
                }
            } // A user form submission error occurred, handled below.
        } // Form submission.
        
        // Make the normal view.
        
    }

}

/* End of file estimate.php */
/* Location: ./application/controllers/estimate.php */